/*
 * Dijjer - A Peer to Peer HTTP Cache
 * Copyright (C) 2004,2005 Change.Tv, Inc
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package dijjer.util;

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author ian
 * 
 * To change the template for this generated type comment go to Window - Preferences - Java - Code Generation - Code and
 * Comments
 */
public class Crypto {
	public static byte[] toByteArray(PublicKey pk) {
		return pk.getEncoded();
	}
	
	public static byte[] toByteArray(PrivateKey pk) {
		return pk.getEncoded();
	}
	
	public static PublicKey toPublicKey(byte[] ba) {
		try {
		X509EncodedKeySpec eks = new X509EncodedKeySpec(ba);
		return KeyFactory.getInstance("RSA").generatePublic(eks);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static PrivateKey toPrivateKey(byte[] ba) {
		try {
		PKCS8EncodedKeySpec eks = new PKCS8EncodedKeySpec(ba);
		return KeyFactory.getInstance("RSA").generatePrivate(eks);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static KeyPair genKeyPair() {
		try {
			KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
			random.setSeed(System.currentTimeMillis());
			keyGen.initialize(1024, random);
			return keyGen.generateKeyPair();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static byte[] generateSignature(PrivateKey privKey, byte[] data) {
		try {
		Signature rsa = Signature.getInstance("SHA1withRSA");
		rsa.initSign(privKey);
		rsa.update(data);
		return rsa.sign();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static boolean checkSignature(byte[] signature, PublicKey pubKey, byte[] data) {
		try {
		Signature rsa = Signature.getInstance("SHA1withRSA");
		rsa.initVerify(pubKey);
		rsa.update(data);
		return rsa.verify(signature);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
